package cn.tedu.store.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.DesensitizedUtil;
import cn.tedu.store.config.util.PDFUtils;
import cn.tedu.store.config.util.RequestUtils;
import cn.tedu.store.config.util.StringUtil;
import cn.tedu.store.entity.LisResult;
import cn.tedu.store.entity.LisTestReg;
import cn.tedu.store.entity.LisWorkgroup;
import cn.tedu.store.service.LisResultService;
import cn.tedu.store.service.ListTestRegService;
import cn.tedu.store.service.PeopleGroupService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsProject: demo_hesuan
 * @BelongsPackage: cn.tedu.store.controller
 * @Author: JunFu
 * @CreateTime: 2022-09-15  08:14
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
@Controller
@Slf4j
@RequestMapping("export")
public class ExportController {
    @Autowired
    private LisResultService lisResultService;
    @Autowired
    private ListTestRegService listTestRegService;
    @Autowired
    PeopleGroupService peopleGroupService;

    private  static final String url="https://api.weixin.qq.com/tcb/batchdownloadfile?access_token=ACCESS_TOKEN";

    @PostMapping("/download")
    public void download(HttpServletResponse response, HttpServletRequest request) throws Exception {
        //2.生成静态页
        Map<String, Object> data = buildData(request, response);
        try (BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {
            response.setContentType(MediaType.APPLICATION_PDF_VALUE);
            response.setCharacterEncoding(PDFUtils.ENCODING);
            String patientname = data.get("PATIENTNAME").toString();
            String name = new String(patientname.getBytes("utf-8"), "iso-8859-1") + ".pdf";
            response.setHeader("Content-Disposition", "attachment;filename=" + name + ".pdf");
            //PDFUtils  是修改过后
            PDFUtils.createPDF("zjTemplates.ftl", data, out);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据不存在");
        }
    }
    private Map<String, Object> buildData(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        //通过工具类获取json数据
        JSONObject jsonObject = RequestUtils.requestJsonString(request);
        System.out.println("1111111111111111111111111111111111");
        log.info("request:",request);
        log.info("jsonObject：",jsonObject);
        String idEnNo = jsonObject.get("idEnNo").toString();
        String barCode = jsonObject.get("barCode").toString();
        System.out.println("2222222222222222222222222222222");
        log.info(idEnNo);
        log.info(barCode);
        //查询病人详情表 用集合封装是为了 把医院名字带过来数据库没有医院名字 我们配置的是多数据源 但用户的查询会带一个唯一标识 我们会一个一个数据库去查询把病人信息查出来
        Map<String, LisTestReg> oneRegMap = listTestRegService.getOneReg(idEnNo, barCode);
        //取医院名称和病人详情表
        Map.Entry<String, LisTestReg> next = oneRegMap.entrySet().iterator().next();
        String key = next.getKey();
        LisTestReg oneLisTestReg = oneRegMap.get(key);
        //testdate是索引会提高查询效率 不过在第一个表里的testdate是date类型而我们检验表里testdate是前八位String因此需要进行转
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = formatter.format(oneLisTestReg.getTestDate());
        String testDate = StringUtil.toAll(format, 0, 8);

        //身份证号
        String idCardNum = DesensitizedUtil.idCardNum(oneLisTestReg.getIdEnNo(), 4, 4);
//        System.out.println(idCardNum);
        //查询检测表
//        System.out.println(testDate + oneLisTestReg.getMachineCode());
        LisResult result = lisResultService.getOneResult(testDate, oneLisTestReg.getHisItemCode(), oneLisTestReg.getMachineCode());

        //查询检验者签名
        LisWorkgroup sign = peopleGroupService.getSign(oneLisTestReg.getGetSampleTesterId(), oneLisTestReg.getGetSampleTesterName());
        //查询审核者签名
        LisWorkgroup audit = peopleGroupService.getAudit(oneLisTestReg.getAdjustSampleTesterId(), oneLisTestReg.getAdjustSampleTesterName());

        map.put("IDENNO", idCardNum);//身份证号
        map.put("DOCTORDEPTNAME", key);//医院
        map.put("PATIENTNAME", oneLisTestReg.getPatientName());//姓名
        map.put("MACHINECODE", oneLisTestReg.getMachineCode());//检验仪器
        map.put("BARCODE", oneLisTestReg.getBarCode());//条形码
        map.put("PATIENTSEX", oneLisTestReg.getPatientSex());//性别
        map.put("SAMPLETYPE", oneLisTestReg.getSampleType());//标本类别
        map.put("HIS_ITEMNAME", oneLisTestReg.getHisItemName());//检测项目
        map.put("PATIENTTYPE", oneLisTestReg.getPatientType());//患者类别
        map.put("PATIENTAGE", oneLisTestReg.getPatientAge());//年龄
        map.put("DIAGNOSE", oneLisTestReg.getDiagnose());//诊断
        map.put("BEDNO", oneLisTestReg.getBedNo());//床号
        map.put("TESTFORMNO", oneLisTestReg.getTestFormNo());//样本号
        map.put("NURSEID", oneLisTestReg.getNurseId());//抽取样品护士id
        map.put("PATIENTNO", oneLisTestReg.getPatientNo());//患者卡号
        map.put("GETSAMPLEDATE", oneLisTestReg.getGetSampleDate());//接收时间
        map.put("GETSAMPLETESTERNAME", oneLisTestReg.getGetSampleTesterName());//检验者名称
        map.put("ADJUSTSAMPLETESTERNAME", oneLisTestReg.getAdjustSampleTesterName());//审核者名称
        map.put("RESULTDATE", oneLisTestReg.getResultDate());//时间
        map.put("HIS_ITEMCODE", oneLisTestReg.getHisItemName());//检测方法
        map.put("P", toPhoto(sign));//检验路径
        map.put("V", toPhoto(audit));//审核路径
        //检验方法及检测限
        map.put("RANGE", result.getRange());//参考范围
        map.put("RESULT", result.getResult());//结果
        map.put("ITEMCODE", result.getItemcode());//编码
        map.put("ITEMNAME", result.getItemname());//项目
        map.put("MEMO", result.getMemo());//备注
        map.put("UNIT", result.getUnit());//单位
        return map;
    }

    //private String url = "<img src= \" & \" >";
    //生成本地签名
    private String toPhoto(LisWorkgroup sign) throws IOException {
        String url = "data:image/jpg;base64,";
        //判断图片二进制是否存在，存在就直接给它byte的base64编码
        if (null == sign.getCaPersonName()) {
            return sign.getPersonName();
        } else {
            String encode = Base64.encode(sign.getCaPersonName());
            return "<img src="+"\""+"data:image/jpg;base64,"+Base64.encode(sign.getCaPersonName())+"\""+" width=\"40\" height=\"30\""+"/>";
        }
    }


}
